package com.homevip.util;

import com.homevip.user.entity.User;
import com.homevip.util.system.Const;

import javax.servlet.http.HttpServletRequest;

/**
 * 关于用户session操作
 * 
 * @author root
 * 
 */
public class UserSessionUtil {

	/**
	 * 保存验证码
	 * @param request
	 * @return
	 */
	public static void setRandCode(String code, HttpServletRequest request) {
		request.getSession().setAttribute(Const.SESSION_KEY_RAND, code);
	}
	
	/**
	 * 返回验证码
	 * @param request
	 * @return
	 */
	public static String getRandCode(HttpServletRequest request) {
		return (String) request.getSession().getAttribute(Const.SESSION_KEY_RAND);
	}

	/**
	 * @param user
	 * @param request
	 */
	public static void setUser(User user, HttpServletRequest request) {
		if (user == null || user.getId() == 0) {
			return;
		}
		request.getSession().invalidate();
		request.getSession().setAttribute(Const.SESSION_KEY_USER, user);
	}

	/**
	 * @param request
	 */
	public static User getUser(HttpServletRequest request) {
		return (User) request.getSession().getAttribute(Const.SESSION_KEY_USER);
	}

	/**
	 * 移除后台用户
	 * @param request
	 */
	public static void removeUser(HttpServletRequest request) {
		request.getSession().removeAttribute(Const.SESSION_KEY_USER);
	}
	
	/**
	 * @param user
	 * @param request
	 */
	public static void updateUser(User user, HttpServletRequest request) {
		if (user == null || user.getId() == 0) {
			return;
		}
		request.getSession().setAttribute(Const.SESSION_KEY_USER, user);
	}
}